import { Select } from 'antd';
import React, { Component, useState, useEffect } from 'react';

let { Option } = Select;

const Cascader = ({
  value,
  onChange,
  option,
  resetkey,
  form,
  mode,
  placeholder,
  rowkey,
  disabledlist,
  setvalueEnum
}) => {
  const [innerOptions, setOptions] = useState([]);
  useEffect(() => {
    if (Array.isArray(option)) {
      setOptions(() => {
        let valueEnum = {};
        let options = option.map((it) => {
          let val = rowkey ? it[rowkey] : it.value;
          valueEnum[val] = {
            text: it.label
          }
          return {
            label: it.label,
            value: val,
            disabled:
              disabledlist && disabledlist.some((item) => item == it[rowkey] || item == it.label),
          }
        });
        setvalueEnum && setvalueEnum(valueEnum)
        return options
      });
    } else {
      option.database(option.params).then((res) => {
        setOptions(() => {
          let valueEnum = {};
          let options = res.data.dataList.map((it) => {
            let val = rowkey ? it[rowkey] : it.value;
            valueEnum[val] = {
              text: it.label
            }
            return {
              label: it.label,
              value: val,
              disabled:
                disabledlist && disabledlist.some((item) => item == it[rowkey] || item == it.label),
            }
          });
          setvalueEnum && setvalueEnum(valueEnum);
          return options
        });
      });
    }
  }, [JSON.stringify(option)]);

  return (
    <Select
      showSearch
      mode={mode || ''}
      placeholder={placeholder || '请选择'}
      allowClear
      style={{ width: '100%' }}
      options={innerOptions}
      value={value}
      onChange={(val) => {
        console.log(0);
        onChange(val);
        if (resetkey) {
          resetkey.map((it) => {
            form.setFieldsValue({ [it]: null });
          });
        }
      }}
    />
  );
};

export default Cascader;
